<?php
// https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/submissions/
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */

class Solution {

    /**
     * @param TreeNode $root
     * @return NULL
     */
    function flatten($root) {
        if ($root == null) {
            return null;
        }
        // 后序遍历，最后交换根节点
        $this->flatten($root->left);
        $this->flatten($root->right);

        // 1、左右子树已经被拉平成一条链表
        $left = $root->left;
        $right = $root->right;

        // 2、将左子树作为右子树
        $root->left = null;
        $root->right = $left;

        // 3、将原先的右子树接到当前右子树的末端
        $p = $root;
        while ($p->right != null) {
            $p = $p->right;
        }
        $p->right = $right;

        return $p;
    }
}